// pages/work/detail/todoDetail.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nextNodes: [],
    obj: null,
    inputShowed: false,
    inputVal: "",
    tabs: ["工单信息", "处理信息", "催单信息"],
    activeIndex: 0,
    sliderOffset: 4,
    sliderLeft: 0,
    arrayIndex:0,//提交环节index
    showIndex1:1,//基本信息面板展开
    showIndex2:2,//客户信息面板展开
    showIndex3:3,//处理情况
    workActiveIndex:0,//工单待处理：0 工单已处理：1
    selPerson:{"id":'',"userName":''},//选择处理人的id
    formDatas: { docId: '', formId: '', preNodeid: '', preNodeName:''},
    remark:null,
    loadingHidden:false,
    isShowForm:false//工单处理表单是否显示
  },
  //备注输入
  inputRemark(e){
    console.log(e);
    this.setData({
      remark: e.detail.value
    });
    console.log("remark:"+this.data.remark);
  },
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft + 13,
      activeIndex: e.currentTarget.id
    });
  },
  //关闭
  closeForm(e) {
    wx.reLaunch({
      url: '../index'
    });
  },
 //选择处理人 
  selPerson(e){
    wx.navigateTo({
      url: 'selPerson'
    })
  },
  //工单信息面板折叠展开操作
  panel: function (e) {
    var i = 0
    if (e.currentTarget.dataset.index == 1){
      if (e.currentTarget.dataset.index != this.data.showIndex1) 
        i = e.currentTarget.dataset.index; 
      this.setData({
        showIndex1: i
      })
    } else if (e.currentTarget.dataset.index == 2){
      if (e.currentTarget.dataset.index != this.data.showIndex2)
        i = e.currentTarget.dataset.index;
      this.setData({
        showIndex2: i
      })
    }else{
      if (e.currentTarget.dataset.index != this.data.showIndex3)
        i = e.currentTarget.dataset.index;
      this.setData({
        showIndex3: i
      })
    }
  },
  //选择提交环节
  bindNodeChange: function (e) {
    var index = e.detail.value;
    console.log('picker发送选择改变，携带值为', index)
    var currentId = this.data.nextNodes[index].id; // 这个id就是选中项的id
    var currentNodeName = this.data.nextNodes[index].nodeName;
    this.setData({
      arrayIndex: index,
      currentNodeid: currentId,
      currentNodeName: currentNodeName
    })
  },
  //提交工单执行
  formSubmit(e) {
    console.log(e);
    var _this = this;
    var formDatas = _this.data.formDatas;
    formDatas.token = app.data.token;
    formDatas.remark = _this.data.remark;
    formDatas.currentUserName = _this.data.selPerson.userName;
    formDatas.currentUserid = _this.data.selPerson.id;
    formDatas.currentNodeid = _this.data.currentNodeid;
    formDatas.currentNodeName = _this.data.currentNodeName;
    var that = this;
    var warn = "";//弹框时提示的内容
    var flag = false;//判断信息输入是否完整
    if (formDatas.currentUserName == null || formDatas.currentUserName == ''){
      flag = true;
      warn = "请选择处理人！";
    }
    if (formDatas.preNodeName == null || formDatas.preNodeName == '') {
      flag = true;
      warn = "请选择提交环节！";
    }
    if (formDatas.remark == null || formDatas.remark == '') {
      flag = true;
      warn = "请输入处理意见！";
    }
    //如果信息填写不完整，弹出输入框
    if (flag == true) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: warn
      })
    }else{
      that.doSubmit(that, formDatas);
    }  
  },
  doSubmit(_this,params){
    _this.setData({
      loadingHidden: false
    });
    wx.request({
      url: getApp().data.app_server + "/weixin/workorder/runProcess",
      method: 'post',
      data: params,
      header: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      success: function (res) {
        console.log(res);
        app.data.selPerson = { "id": '', "userName": '' };
        var msg = res.data.code == 200 ? '操作成功' : '操作失败';
        wx.showModal({//无论成功失败都会提示响应信息
          title: '提示',
          showCancel: false,
          content: msg,
          success: (r) => {
            _this.setData({
              loadingHidden: true
            });
            if (res.data.code == 200) {//登录成功,饭hi列表
              _this.getUndoWorkCount(_this,app.data.token);
              wx.navigateTo({
                url: '../index'
              }) 
            }
          }
        });
      }
    })
  },
  //确认接单
  orderConfirm(){
    var _this = this;
    var formDatas = _this.data.formDatas;
    _this.setData({
      loadingHidden: false
    });
    wx.request({
      url: getApp().data.app_server + "/weixin/workorder/orderConfirm",
      method: 'post',
      data: {
        token:app.data.token,
        id: formDatas.formId,//工单id
        nodeId: formDatas.preNodeid,//当前节点id
        nodeName: formDatas.preNodeName,//当前节点名称
        docId: formDatas.docId//流程实例id
      },
      header: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      success: function (res) {
        app.data.selPerson = { "id": '', "userName": '' };
        _this.setData({
          loadingHidden: true
        });
        console.log(res);
        var msg = res.data.code == 200 ? '操作成功' : '操作失败';
        wx.showModal({//无论成功失败都会提示响应信息
          title: '提示',
          showCancel: false,
          content: msg,
          success: (r) => {
            if (res.data.code == 200) {//登录成功,返回列表
              _this.getUndoWorkCount(_this, app.data.token);
              _this.getDetails(_this.data.id);
            }
          }
        });
      }
    })
  },
  //非本职返回客服--重新指派
  orderReassign(){
    var _this = this;
    var formDatas = _this.data.formDatas;
    formDatas.remark = _this.data.remark;
    console.log('请输入处理意见！' + formDatas.remark );
    if (formDatas.remark == null || formDatas.remark == '') {
      console.log('请输入处理意见！');
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: "请输入处理意见！"
      })
    } else {
      _this.setData({
        loadingHidden: false
      });
      wx.request({
        url: getApp().data.app_server + "/weixin/workorder/orderReassign",
        method: 'post',
        data: {
          token: app.data.token,
          id: formDatas.formId,//工单id
          nodeId: formDatas.preNodeid,//当前节点id
          nodeName: formDatas.preNodeName,//当前节点名称
          docId: formDatas.docId,//流程实例id
          remark: _this.data.remark
        },
        header: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        success: function (res) {
          app.data.selPerson = { "id": '', "userName": '' };
          _this.setData({
            loadingHidden: true
          });
          console.log(res);
          var msg = res.data.code == 200 ? '操作成功' : '操作失败';
          wx.showModal({//无论成功失败都会提示响应信息
            title: '提示',
            showCancel: false,
            content: msg,
            success: (r) => {
              if (res.data.code == 200) {//登录成功,返回列表
                _this.getUndoWorkCount(_this, app.data.token);
                wx.navigateTo({
                  url: '../index'
                })
              }
            }
          });
        }
      })
    } 
    
  },
  //待处理工单条数
  getUndoWorkCount(_this, token) {
    wx.request({
      url: app.data.app_server + "/weixin/workorder/count",
      method: 'post',
      data: {
        token: token,
        status: 0//0未读 1已读 空值获取全部
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        app.data.undoWorkCount = res.data.msg
        console.log("getUndoWorkCount:" + app.data.undoWorkCount)
      }
    })
  },
  //查看工单详情POST /weixin/workorder/openProcess
  getDetails(id, workActiveIndex, userId) {
    let nextNodes = [];
    let _this = this;
    wx.request({
      url: getApp().data.app_server + "/weixin/workorder/openProcess",
      method: 'post',
      data: { id: id },
      header: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      success: function (res) {
        console.log(res);
        let data = res.data.msg;
        if (data.remarks != null ){
          for (var i = 0; i < data.remarks.length; i++){
            data.remarks[i].createTime = data.remarks[i].createTime.replace(/-/g,'.');
          }
        }
        var arrayIndex = 0;
        if(data.node != null){
          nextNodes = data.node.nextNodes;
          if (nextNodes != null ){
            for (var j = 0; j < nextNodes.length; j++){
              if (nextNodes[j].nodeName == '客服回访'){
                arrayIndex = j;
              }
            }
          }
        }
        var isShowForm = false;
        if (_this.data.workActiveIndex == 0 && data.document.currentUserid == app.data.userId){
          isShowForm = true;
        }
        var docId = data.document != null ? data.document.id : null;
        var formId = data.workOrder != null ? data.workOrder.id : null;
        var preNodeid = data.node != null ? data.node.id : null;
        var preNodeName = data.node != null ? data.node.nodeName : null;
        _this.setData({
          obj: data,
          nextNodes: nextNodes,
          arrayIndex: arrayIndex,
          ['formDatas.docId']: docId,
          ['formDatas.formId']: formId,
          ['formDatas.preNodeid']: preNodeid,
          ['formDatas.preNodeName']: preNodeName,
          loadingHidden: true,
          currentNodeid: nextNodes[arrayIndex].id,
          currentNodeName: nextNodes[arrayIndex].nodeName,
          workActiveIndex: workActiveIndex,
          userId: userId,
          isShowForm: isShowForm
        })

      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      workActiveIndex: options.workActiveIndex,
      userId:app.data.userId,
      id: options.id
    });
    this.getDetails(options.id, options.workActiveIndex, app.data.userId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

   this.setData({
      selPerson:app.data.selPerson
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})